import { View } from "@tarojs/components";
import PetMoment from "../petMoment";
import { IMG_URL } from "@/constants/api";
import { AtActionSheet, AtActionSheetItem } from "taro-ui";
import { useState } from "react";

import "taro-ui/dist/style/components/action-sheet.scss";
import "taro-ui/dist/style/components/icon.scss";
import "./index.scss";
import apiRequest from "@/service/apiRequest";
import Taro from "@tarojs/taro";

function PetMomentList({list, refreshList}: {list: Array<PetMomentItem>, refreshList: Function}) {
  console.log(refreshList, 'refreshList');
  
  const [openStatus, setOpenStatus] = useState(false);
  const [currentMomentItem, setPetMomentItem] = useState<PetMomentItem>();

  const handleAction = (item: any) => {
    setOpenStatus(true);
    setPetMomentItem(item);
  }
  
  const handleCancel = () => {
    setOpenStatus(false);
  }
  
  const handleClose = () => {
    setOpenStatus(false);
  }
  
  const handleDeleteItem = async () => {
    handleClose();
    setTimeout(() => {
      Taro.showModal({
        title: '提示',
        content: '是否确认删除该动态？',
        success: async (res) => {
          if (res.confirm) {
            const res = await requestDeleteMoment();
            if (res) {
              Taro.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              refreshList && refreshList(currentMomentItem?.id);
            }
          }
        }
      })
    }, 300);
  }

  const requestDeleteMoment = async () => {
    if (!currentMomentItem) {
      return
    }
    const res = await apiRequest.post(`/api/posts/remove/${currentMomentItem.id}`);
    return res ? res.result : false;
  }

  return (
    <View>
      {
        list && list.length ? list.map((item, index) => (
          <PetMoment
            key={index}
            userAvatar={item.userAvatar || `${IMG_URL}/avatar.png`}
            userName={item.userName}
            agoTime={item.agoTime}
            content={item.content}
            images={item.images}
            onAction={() => handleAction(item)}
          />
        )) : null
      }
      {/* 操作 */}
      <AtActionSheet isOpened={openStatus} cancelText='取消' title='操作当前的动态' onCancel={handleCancel} onClose={handleClose}>
        <AtActionSheetItem onClick={handleDeleteItem}>
          <View className="flex-a-c delete-item">
            <View className='at-icon at-icon-trash'></View>
            <View className="item">删除</View>
          </View>
        </AtActionSheetItem>
      </AtActionSheet>
    </View>
  )
}

export default PetMomentList;